package com.qigao.erp.service.impl;

import com.qigao.erp.api.DataStoreService;
import com.qigao.erp.api.LoginInfoService;
import com.qigao.erp.commons.SysResourcePermitService;
import com.qigao.erp.commons.SysUserRoleService;
import com.qigao.erp.commons.dto.SysResourcePermitResultDto;
import com.qigao.erp.commons.dto.SysUserRoleResultDto;
import com.qigao.erp.commons.dto.UserModiPassDto;
import com.qigao.erp.commons.dto.UserRegisterDto;
import com.qigao.erp.commons.enums.*;
import com.qigao.erp.commons.po.UserInfo;
import com.qigao.erp.commons.po.UserPermit;
import com.qigao.erp.commons.po.UserPermitResult;
import com.qigao.erp.commons.utils.DateUtil;
import com.qigao.erp.commons.utils.ThreeDESUtil;
import com.qigao.erp.jdbc.mapper.SysUserMapper;
import com.qigao.erp.jdbc.model.SysUser;
import com.qigao.erp.service.core.LoginCoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户登录表 服务实现类
 * </p>
 *
 * @author luiz
 * @since 2019-04-03
 */
@Service
public class LoginInfoServiceImpl implements LoginInfoService {
    private static final Logger logger = LoggerFactory.getLogger(LoginInfoServiceImpl.class);
    @Resource
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysResourcePermitService sysResourcePermitService;
    @Resource
    DataStoreService dataStoreService;
    @Resource
    private LoginCoreService loginCoreService;



    @Override
    public Result findByLoginNo(String loginNo) {
        SysUser sysUser = sysUserMapper.selectByIndex(loginNo);
        if (sysUser == null) {
            return Result.newError(ResultCode.USER_NOT_EXISTS);
        }
        UserInfo userInfo = buildResultInfo(sysUser);
        return Result.newSuccess(userInfo);
    }

    @Override
    public Result doLogin(String loginNo, String loginPass) {
        String encryptPass = ThreeDESUtil.encryptToHex(loginPass);
        SysUser tkUser = sysUserMapper.selectByPhoneNum(loginNo);
        if (tkUser == null) {
            return Result.newError(ResultCode.USER_NOT_EXISTS);
        }
        if (StatusEnum.VALID.getCode() != tkUser.getStatus()) {
            return Result.newError(ResultCode.USER_HAS_LOCK);
        }
        if (!tkUser.getLoginPass().equals(encryptPass)) {
            return Result.newError(ResultCode.USERNAME_OR_PASS_ERR);
        }
        UserInfo userInfo = buildResultInfo(tkUser);
        //登录成功，则修改登录信息
        // 开始进入shiro的认证流程
        //ShiroUtils.login(token);
        return Result.newSuccess(userInfo);
    }

    /**
     * 修改密码
     *
     * @param userModiPassDto
     * @return
     */
    @Override
    public Result doModiPass(UserModiPassDto userModiPassDto) {
        SysUser sysUser = sysUserMapper.selectByIndex(userModiPassDto.getLoginNo());
        if (sysUser == null) {
            return Result.newError(ResultCode.USER_NOT_EXISTS);
        }
        String signPass = ThreeDESUtil.encryptToHex(userModiPassDto.getOldPass());
        if (!sysUser.getLoginPass().equals(signPass)) {
            return Result.newError(ResultCode.USER_OLD_PASS_ERROR);
        }
        if (!userModiPassDto.getPasswordNew1().equals(userModiPassDto.getPasswordNew2())) {
            return Result.newError(ResultCode.USER_PASS_NOT_EQUAL);
        }
        String pass1 = userModiPassDto.getPasswordNew1();
        if (pass1.contains(userModiPassDto.getLoginNo())) {
            return Result.newError(ResultCode.PASS_CANNOT_CONTAINS_ACCOUNT);
        }
        String signPass1 = ThreeDESUtil.encryptToHex(pass1);
        sysUser.setLoginPass(signPass1);
        sysUser.setModiTime(new Date());
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
        return Result.newSuccess();
    }



    /**
     * 存储用户信息
     * @param sysUser
     */
    private SysUser saveUserInfo(SysUser sysUser) {
        SysUser oldUser=sysUserMapper.selectByUserNo(sysUser.getUserNo());
        if(oldUser==null){
            sysUserMapper.insertSelective(sysUser);
            return sysUser;
        }
        return oldUser;
    }



    private UserInfo buildResultInfo(SysUser sysUser) {
        UserInfo userInfo = new UserInfo();
        String userNo = sysUser.getUserNo();
        BeanUtils.copyProperties(sysUser, userInfo);
        userInfo.setCreateTime(DateUtil.getDateTimeFormat(sysUser.getCreateTime()));
        userInfo.setModiTime(DateUtil.getDateTimeFormat(sysUser.getModiTime()));
        Integer userStatus=sysUser.getStatus();
        int status=userStatus==null?0:userStatus;
        userInfo.setStatus(status);
        userInfo.setStatusName(StatusEnum.getNameByCode(status));
        Integer ifAdmin=sysUser.getIfAdmin();
        int ifAdminInt=ifAdmin==null?0:ifAdmin;
        userInfo.setIfAdmin(ifAdminInt);
        userInfo.setIfAdminName(IfAdminEnum.getNameByCode(ifAdminInt));
        userInfo.setUserTypeName(UserTypeEnum.getNameByCode(userInfo.getUserType()));
        userInfo.setUserSourceName(UserSourceEnum.getNameByCode(userInfo.getUserSource()));
        Result<List<SysUserRoleResultDto>> sysUserRoleResult = sysUserRoleService.findByUserNo(userNo);
        List<SysUserRoleResultDto> sysUserRoleResultDtos = sysUserRoleResult.getData();
        List<String> groupList = new ArrayList<>();
        List<UserPermit> userPermits = new ArrayList<>();
        if (sysUserRoleResult.isSuccess() && sysUserRoleResultDtos != null && sysUserRoleResultDtos.size() >= 1) {
            for (SysUserRoleResultDto sysUserRoleResultDto : sysUserRoleResultDtos) {
                groupList.add(sysUserRoleResultDto.getRoleCode());
                userPermits=buildPermit(sysUserRoleResultDto.getRoleCode(),SourceTypeEnum.ROLE.getCode());
            }
        }
        userInfo.setSysUserRoleResultDtos(sysUserRoleResultDtos);
        userInfo.setUserGroups(groupList);
        userPermits.addAll(buildPermit(userNo,SourceTypeEnum.USER.getCode()));
        userInfo.setUserPermits(userPermits);
        /*List<ShopEmpResultDto> shopEmpResultDtos=shopEmpService.findByEmpNo(sysUser.getUserNo());
        List<MerShopInfo> merShopInfos=null;
        if(!CollectionUtils.isEmpty(shopEmpResultDtos)){
            merShopInfos=new ArrayList<>();
            for(ShopEmpResultDto shopEmpResultDto:shopEmpResultDtos){
                MerShopInfo merShopInfo=new MerShopInfo();
                merShopInfo.setShopNo(shopEmpResultDto.getShopNo());
                ShopInfoDto shopInfoDto=shopInfoService.findByShopNo(shopEmpResultDto.getShopNo());
                merShopInfo.setShopName(shopInfoDto.getShopName());
                merShopInfo.setMerNo(shopInfoDto.getMerNo());
                merShopInfo.setMerName(shopInfoDto.getMerName());
                int countNum=merAdminService.countEnableNum(shopInfoDto.getMerNo(),sysUser.getUserNo());
                merShopInfo.setIfMerAdmin(IfAdminEnum.NO);
                if (countNum>=1){
                    merShopInfo.setIfMerAdmin(IfAdminEnum.YES);
                }
                merShopInfos.add(merShopInfo);
            }
        }
        userInfo.setMerShopInfos(merShopInfos);*/
        return userInfo;
    }

    @Override
    public List<UserPermitResult> getCurrentUserPermit(String userNo) {
        List<UserPermitResult>  userPermitResults=sysResourcePermitService.selectLevelOne(userNo);
        for(UserPermitResult userPermitResult:userPermitResults){
           String resourceNo = userPermitResult.getResourceNo();
            List<UserPermitResult>  userPermitResultList=buildChildPermit(userNo,resourceNo,userPermitResult);
          //  userPermitResult.setChildPermits(userPermitResultList);
        }
        return userPermitResults;
    }
    private List<UserPermitResult> buildChildPermit(String userNo,String resourceNo, UserPermitResult userPermitResult) {
        List<UserPermitResult>  userPermitResults=sysResourcePermitService.selectChild(userNo,resourceNo);
        userPermitResult.setChildPermits(userPermitResults);
        if(CollectionUtils.isEmpty(userPermitResults))return userPermitResults;
        for(UserPermitResult userPermitResult1:userPermitResults){
            buildChildPermit(userNo,userPermitResult1.getResourceNo(),userPermitResult1);
        }
        return null;
    }

    private List<UserPermit> buildPermit(String sourceCode,String sourceType) {
        List<UserPermit> userPermits = new ArrayList<>();
        Result<List<SysResourcePermitResultDto>> resourcePermitResult= sysResourcePermitService.findByIndex(sourceCode,sourceType);
        List<SysResourcePermitResultDto> sysResourcePermitResultDtos = resourcePermitResult.getData();
        if (resourcePermitResult.isSuccess() && sysResourcePermitResultDtos != null && sysResourcePermitResultDtos.size() >= 1) {
            for (SysResourcePermitResultDto sysResourcePermitResultDto : sysResourcePermitResultDtos) {
                UserPermit userPermit = new UserPermit();
                userPermit.setGroupNo(sysResourcePermitResultDto.getSourceCode());
                userPermit.setResourceNo(sysResourcePermitResultDto.getResourceNo());
                userPermit.setPreSourceNo(sysResourcePermitResultDto.getPresourceNo());
                userPermit.setResourceName(sysResourcePermitResultDto.getResourceName());
                userPermit.setResourceType(sysResourcePermitResultDto.getResourceType());
                userPermit.setReqUrl(sysResourcePermitResultDto.getReqUrl());
                userPermit.setResourceIcon(sysResourcePermitResultDto.getResourceIcon());
                userPermit.setResourceLevel(sysResourcePermitResultDto.getResourceLevel());
                userPermits.add(userPermit);
            }
        }
        return userPermits;
    }


    @Override
    @Transactional
    public Result doRegister(UserRegisterDto userRegisterDto) {
        //用户注册
        return loginCoreService.doRegister(userRegisterDto);
    }

    @Override
    public Result activeUser(String activeCode) {
        //用户激活
        return loginCoreService.activeUser(activeCode);
    }



    @Override
    public Result forgetPass(String emailAddr) {
        //忘记密码
        return loginCoreService.forgetPass(emailAddr);
    }

    @Override
    public Result modiForgetPass(UserModiPassDto userModiPassDto) {
        //重置密码
        return loginCoreService.modiForgetPass(userModiPassDto);
    }



}
